import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html_2/flutter_html_2.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:lcapp/api/interface/comcon_api.dart';
import 'package:lcapp/api/interface/zixun_api.dart';
import 'package:lcapp/api/request/response_data.dart';
import 'package:lcapp/basic/user_info.dart';
import 'package:lcapp/config/const_config.dart';
import 'package:lcapp/data/comment_data_entity.dart';
import 'package:lcapp/data/zixun_data_entity.dart';
import 'package:lcapp/model/param/base_param.dart';
import 'package:lcapp/model/refresh/refresh.dart';
import 'package:lcapp/model/toast/toast.dart';
import 'package:lcapp/page/home/comment_item.dart';
import 'package:lcapp/page/home/home_share_page.dart';
import 'package:lcapp/page/home/zixun_detail_item.dart';
import 'package:lcapp/page/home/zixun_detail_set_font.dart';
import 'package:lcapp/widget/asr_app_bar.dart';
import 'package:lcapp/widget/asr_html.dart';
import 'package:lcapp/widget/lc_gesture_detector.dart';

import 'home_zixun_item.dart';

class ZixunDetailPage extends StatefulWidget {
  final int zid;
  const ZixunDetailPage({Key? key, required this.zid}) : super(key: key);

  @override
  _ZixunDetailPageState createState() => _ZixunDetailPageState();
}

class _ZixunDetailPageState extends State<ZixunDetailPage> {

  TextEditingController controller = TextEditingController();
  FocusNode focusNode = FocusNode();
  bool isEdit = false;
  int pageNum = 1;
  int pageSize = 10;
  List<CommentDataEntity> comments = [];
  ZixunDataEntity entity = ZixunDataEntity();
  int total=0;
  int replyId = 0;
  double fontSize = 32.sp;
  GlobalKey    commentKey = GlobalKey();
  ScrollController scrollController = ScrollController();
  String hideText = '写评论';
  // List<ZixunDataEntity> zixuns = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getZixunDetail();
    // getZixun();
    focusNode.addListener((){

      if (focusNode.hasFocus) {
        Scrollable.ensureVisible(commentKey.currentContext!);
       }else{
      }
    });
  }

  @override
  void dispose(){
    super.dispose();
    focusNode.dispose();
  }

  getZixunDetail()async{

    ResponseData res = await ZiXunAPI.getZiXunDetail(widget.zid,);
    if(res.code==200&&res.data!=null){
      entity = ZixunDataEntity().fromJson(res.data);
      getComments();
    }
    if(mounted){setState(() {
    });}
  }

  getComments()async{
    ResponseData res = await CommonAPI.getCommentList(entity.id!,pageNum,pageSize);
    if(res.code==200){
      if(pageNum==1){
        comments.clear();
      }
      setState(() {
        total = res.total!;
      List arr = res.data??[];
      arr.forEach((element) {
        CommentDataEntity dataEntity = CommentDataEntity().fromJson(element);
        dataEntity.replies = [];
        comments.add(dataEntity);
      });
      });
    }
 
  }
  saveComment()async{
    if(controller.text.isEmpty){
      showToast('请输入评论内容');
      return;
    }
    ResponseData res;
    showLoading();
    if(replyId!=0){
      res = await CommonAPI.saveCommentReply(replyId,controller.text);
    }else{
      res = await CommonAPI.saveComment(entity.id!, 0, controller.text);
    }
    hideLoading();

    if(res.code==200){
      showToast('发布评论成功');
      controller.text='';
      pageNum=1;
      hideText = '写评论';
      getComments();
    }
  }

  // getZixun()async{
  //   ResponseData res = await ZiXunAPI.getZiXunList(1, 3,articleTypeId: 0);
  //   if(res.code==200){
  //     List arr = res.data??[];
  //     for (var e in arr) {
  //       ZixunDataEntity entity = ZixunDataEntity().fromJson(e);
  //       zixuns.add(entity);
  //     }
  //   }
  //   if(mounted){setState(() {
  //   });}
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: bgColor,
      appBar: AsrAppBar(
        titleText: '资讯详情',
        elevation: 0.0,
        actions: [
          GestureDetector(
            onTap: (){
              SmartDialog.show(
                  alignment: Alignment.bottomCenter,
                  clickMaskDismiss: true,
                  maskColor: Color.fromRGBO(0, 0, 0, 0.75), builder: (BuildContext context) {
                    return ZixunDetailSetSize(
                      fontSize: fontSize,
                      fontBlock: (size){
                        setState(() {
                          fontSize = size;
                        });
                      },);
              },
              );
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 30.w),
              alignment: Alignment.center,
              child: Text('字体大小',style: TextStyle(
                color: Color(0xff666666),
                fontSize: 24.sp,
                fontWeight: FontWeight.w500
              ),),
            ),
          )
        ],
      ),
      body: GestureDetector(
        onTap: (){
          if(controller.text.isEmpty){
            replyId = 0;

          }
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Column(
          children: [
            Expanded(child:Container(
              child: EasyRefresh(
                scrollController: scrollController,
                header: myRefreshHeader(),
                footer: myRefreshFooter(),
                child: Column(
                  children: [
                    Container(
                      color: Colors.white,
                      padding: EdgeInsets.symmetric(horizontal: 30.w),
                      child: Column(
                        children: [
                          Text(entity.title??'',style: TextStyle(
                              color: Colors.black,
                              fontSize: 40.sp,
                              fontWeight: FontWeight.w600
                          ),),
                          Container(
                            margin: EdgeInsets.symmetric(vertical: 30.w),
                            child: Row(children: [
                              Expanded(child: Text(entity.origin??'',style: TextStyle(
                                color: Color(0xff333333),
                                fontSize: 28.sp,
                              ))),
                              Text('${entity.createTime}',style: TextStyle(
                                color: Color(0xff333333),
                                fontSize: 28.sp,
                              ))
                            ],),
                          ),
                          Container(
                            child: Html(
                              data: entity.content??'',
                              style: {
                                'body':Style(
                                  fontSize: FontSize(fontSize),
                                  lineHeight: LineHeight(1.5)
                                ),
                                'p':Style(
                            fontSize: FontSize(fontSize),
                                    lineHeight: LineHeight(1.5)
                            ),
                                'span':Style(
                                  fontSize: FontSize(fontSize),
                                    lineHeight: LineHeight(1.5)
                                ),
                                'h1':Style(
                                  fontSize: FontSize(fontSize),
                                    lineHeight: LineHeight(1.5)
                                ),
                                'strong':Style(
                                  fontSize: FontSize(fontSize),
                                    lineHeight: LineHeight(1.5)
                                ),
                              },
                            ),
                          ),
                          Container(
                            padding: EdgeInsets.symmetric(vertical: 20.w),
                            child: Column(
                              children: [
                                Container(
                                  child: Row(
                                    children: [
                                      Expanded(child: Container(
                                        height: 0.5,
                                        color: Color(0xffD8D8D8),
                                      )),
                                      SizedBox(width: 80.w,),
                                      Text('声明',style: TextStyle(
                                          color: Color(0xff929292),
                                          fontSize: 28.sp
                                      ),),
                                      SizedBox(width: 80.w,),
                                      Expanded(child: Container(
                                        height: 0.5,
                                        color: Color(0xffD8D8D8),
                                      )),
                                    ],
                                  ),
                                ),
                                SizedBox(height: 24.w,),
                                Container(
                                  child: Text(BaseParam.zixunDesx,style: TextStyle(
                                    color: Color(0xff444444),
                                    fontSize: 24.sp
                                  ),),
                                )
                              ],
                            ),
                          )
                        ],
                      ),
                    ),
                    Container(
                      color: Colors.white,
                      margin: EdgeInsets.symmetric(vertical: 20.w,),
                      padding: EdgeInsets.symmetric(horizontal: 30.w),
                      child: Column(
                        children: [
                          Container(
                            margin: EdgeInsets.symmetric(vertical: 30.w),
                            child: Row(
                              children: [
                                Container(width: 5,height: 40.w,color: Color(0xffFF7916),),
                                SizedBox(width: 10.w,),
                                Text('推荐',style: TextStyle(
                                    color: Colors.black,
                                    fontWeight: FontWeight.w600,
                                    fontSize: 30.sp
                                ),),
                              ],
                            ),
                          ),
                          ListView.builder(
                              physics: NeverScrollableScrollPhysics(),
                              padding: EdgeInsets.zero,
                              shrinkWrap: true,
                              itemCount: entity.articleList==null?0: entity.articleList!.length,
                              itemBuilder: (BuildContext context, int i) {
                                return ZixunDetailItem(entity: entity.articleList![i],);
                              })
                        ],
                      ),
                    ),
                    Container(
                      color: Colors.white,
                      padding: EdgeInsets.symmetric(horizontal: 30.w),
                      child: Column(
                        children: [
                          Container(
                            margin: EdgeInsets.symmetric(vertical: 30.w),
                            key: commentKey,
                            child: Row(
                              children: [
                                Container(width: 5,height: 40.w,color: Color(0xffFF7916),),
                                SizedBox(width: 10.w,),
                                Text('共$total条评论',style: TextStyle(
                                    color: Colors.black,
                                    fontWeight: FontWeight.w600,
                                    fontSize: 30.sp
                                ),),
                              ],
                            ),
                          ),
                          ListView.builder(
                              physics: NeverScrollableScrollPhysics(),
                              shrinkWrap: true,
                              padding: EdgeInsets.zero,
                              itemCount: comments.length,
                              itemBuilder: (context,index){
                                return CommentItem(entity: comments[index],commentFun: (cid,name){
                                  replyId = cid;
                                  setState(() {
                                    hideText = '回复@'+name;
                                  });
                                  FocusScope.of(context).requestFocus(focusNode);
                                },);
                              }
                          ),
                        ],
                      ),
                    )
                  ],
                ),
              ),
            )),
            Container(
              padding: EdgeInsets.only(bottom:ScreenUtil().bottomBarHeight>0?20.w:0,left: 30.w,right: 30.w,top: 20.w),
              decoration: BoxDecoration(
                  color: Colors.white
              ),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(child: Container(
                    constraints: BoxConstraints(
                        maxHeight: 200.w
                    ),
                    decoration: BoxDecoration(
                        // color: Colors.green,//Color(0xffEDF1F4),
                        borderRadius: BorderRadius.circular(1000.w)
                    ),
                    padding: EdgeInsets.only(left: 0.w,right: 0,bottom: 20.w),
                    child: Row(
                      children: [
                        // Visibility(child: Container(
                        //   margin: EdgeInsets.only(right: 10.w),
                        //   child: Icon(Icons.edit,color: Color(0xFFAEAEAE),size: 30.w,),
                        // ),visible: isEdit==false,),
                        Expanded(child: Container(
                          child: TextField(
                            controller: controller,
                            focusNode: focusNode,
                            maxLines: null,
                            keyboardType: TextInputType.multiline,
                            textAlign: TextAlign.left,
                            style:  TextStyle(
                              fontSize: 28.sp,
                            ),
                            decoration:  InputDecoration(
                              contentPadding: EdgeInsets.symmetric(horizontal: 20.w,vertical: 10.w),
                              hintText: hideText,
                              hintStyle: TextStyle(
                                color: const Color(0xFFAEAEAE),
                                fontSize: 28.sp,
                                fontWeight: FontWeight.w500,
                              ),
                              counterText: "",
                              border: OutlineInputBorder(
                                borderSide: BorderSide.none,
                                borderRadius: BorderRadius.all(Radius.circular(10.w)),
                              ),
                              fillColor: Color(0xffEDF1F4),
                              filled: true,
                            ),
                            onChanged:(value){
                              setState(() {
                                isEdit = controller.text.isNotEmpty;
                              });
                            },
                          ),
                        ))
                      ],
                    ),
                  )),
                  SizedBox(width: 30.w,),
                  Visibility(
                    child: lcGestureDetector(
                    isLogin:true,
                    onTap: (){
                      FocusScope.of(context).requestFocus(FocusNode());
                      saveComment();
                    },
                    child: Container(
                      padding: EdgeInsets.only(left: 0.w,right: 0,bottom: 20.w),
                      child: Container(
                        height: 80.w,
                        width: 120.w,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            color: defaultBarColor,
                            borderRadius: BorderRadius.circular(6.w)
                        ),
                        child: Text('发送',style: TextStyle(color: Colors.white,fontSize: 24.sp),),
                      ),
                    ),
                  ),visible: controller.text.isNotEmpty,),
                  Visibility(child: Row(
                    children: [
                      lcGestureDetector(
                        isLogin:true,
                        onTap: (){
                          FocusScope.of(context).requestFocus(focusNode);
                        },
                        child: Container(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Image.asset("assets/home/zx_pl.png",width: 40.w,),
                              // SizedBox(height: 2.w,),
                              // Text('发送',style: TextStyle(color: Color(0xffEA6B2B),fontSize: 20.sp),)
                            ],
                          ),
                        ),
                      ),
                      SizedBox(width: 30.w,),
                      lcGestureDetector(
                        isLogin:true,
                        onTap: ()async{

                          ResponseData res = await ZiXunAPI.ziXunCollection(entity.id!, entity.isCollection==0?1:0);
                          if(res.code==200){
                            setState(() {
                              entity.isCollection = entity.isCollection==0?1:0;
                            });
                          }

                        },
                        child: Image.asset(entity.isCollection==0?'assets/home/zx_sc_red.png':'assets/home/zx_sc.png',width: 35.w,),
                      ),
                      SizedBox(width: 30.w,),
                      lcGestureDetector(
                        isLogin:true,
                        onTap: (){
                          if(entity.vipFlag==1){
                            showToast('VIP文章无法分享');
                            return;
                          }
                          SmartDialog.show(
                            alignment: Alignment.bottomCenter,
                            clickMaskDismiss: true,
                            maskColor: Color.fromRGBO(0, 0, 0, 0.5), builder: (BuildContext context) {
                              return HomeSharepage(
                                shareType: entity.layout!=3?2:1,
                                title: entity.title??'粮策-买卖存粮有策略',
                                desc: entity.quote??entity.title??"粮食生意不好做，看不透市场，就来粮策！为您的粮食生意保驾护航！",
                                imgUrl: entity.images,
                                contentType: 0,
                                shareUrl: '${BasVueurl}/#/zixun?lcID=${userInfo.id}&shareId=${entity.id}',
                                zixunDataEntity: entity,
                                map: {
                                  'type':0,
                                  'entryId':entity.id
                                },
                              );
                          },
                          );
                        },
                        child: Image.asset('assets/share/share_gray.png',width: 35.w,),
                      )
                    ],
                  ),visible: controller.text.isEmpty,)
                ],
              ),
            ),
          ],
        ),
      ),
      // bottomNavigationBar:
    );
  }
}

